package v2c04;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author gjunming@gmail.com
 * @version Aug 19, 2009 1:26:50 PM
 */
public class TestDB {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			runTest();
		} catch (SQLException ex) {
			for (Throwable t : ex) {
				t.printStackTrace();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static void runTest() throws SQLException, IOException {
		Connection pgConn = getConnection();

		try {
			Statement pgStat = pgConn.createStatement();

			// pgStat.execcuteUpdate("CREATE TABLE IF NOT EXISTS Greetings(Message CHAR(20))");
			// pgStat.executeUpdate("INSERT INTO greetings VALUES ('hello world')");

			ResultSet pgResult = pgStat.executeQuery("SELECT * FROM greetings");
			if (pgResult.next()) {
				System.out.println(pgResult.getString("Message"));
			}
			pgResult.close();
			pgStat.close();
		} finally {
			pgConn.close();
		}
	}

	public static Connection getConnection() throws SQLException, IOException {
		Properties props = new Properties();
		FileInputStream dbconfig = new FileInputStream(
				"E:\\javaprojects\\java-tutorial\\corejava\\src\\v2c04\\TestDB.properties");
		props.load(dbconfig);
		dbconfig.close();

		String drivers = props.getProperty("jdbc.drivers");
		if (drivers != null) {
			System.setProperty("jdbc.drivers", drivers);
		}
		String url = props.getProperty("jdbc.url");
		String username = props.getProperty("jdbc.username");
		String password = props.getProperty("jdbc.password");

		return DriverManager.getConnection(url, username, password);
	}

}
